import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cart: []
  },
  mutations: {
    // 添加购物车
    cartAdd(state, goods) {
      // 判断购物车中是否存在商品
      let has = state.cart.some(value => {
        if (value.title === goods.title) {
          value.count += goods.count
          return true
        }
      })
      if (!has) {
        state.cart.push({
          title: goods.title,
          price: goods.price,
          count: goods.count,
          select: true,
          id: goods.id
        })
      }
      window.localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    // 初始化更新购物车
    cartInit (state) {
      if (window.localStorage.getItem('cart')) {
        state.cart = JSON.parse(window.localStorage.getItem('cart'))
      }
    },
    // 更新商品数量
    cartUpdate (state, option) {
      state.cart.find(item => {
        if (item.id === option.id) {
          item.count = option.count
          window.localStorage.setItem('cart', JSON.stringify(state.cart))
          return true
        }
      })
    },
    // 删除商品
    cartRemove (state, id) {
      let index = state.cart.findIndex(item => item.id === id)
      if (index != -1) state.cart.splice(index, 1)
      window.localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    // 更新开关选择
    setSelect (state, option) {
      state.cart.some(item => {
        if (item.id === option.id) {
          item.select = option.select
          window.localStorage.setItem('cart', JSON.stringify(state.cart))
          return true
        }
      })
    }
  },
  actions: {

  },
  getters: {
    // 购物车总数
    cartAll (state) {
      let all = 0
      state.cart.forEach(value => all += value.count)
      return all
    },
    // 已选商品
    selectN (state) {
      let n = 0
      state.cart.forEach(item => {
        if (item.select) {
          n++
        }
      })
      return n
    },
    // 已选商品总价
    allPrice (state, getters) {
      let all = 0
      state.cart.forEach(item => {
        if (item.select) {
          all += item.price * item.count
        }
      })
      return all
    }
  }
})
